using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float LeftTime;
    public Rigidbody Rb;

    private void OnEnable()
    {
        LeftTime = 5;
    }
    private void OnDisable()
    {
        Rb.velocity = Vector3.zero;
    }
    private void Update()
    {
        LeftTime -= Time.deltaTime;
        if (LeftTime <= 0)
        {
            BulletPool.Instance.RecoverBullet(this.gameObject);
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        // Debug.Log("碰撞" + other.gameObject.name);
        if (other.gameObject.CompareTag("Wall"))
        {
            // Debug.Log("击中墙壁" + other.transform.position.ToString());

            PlayEffect();
        }
        else if (other.gameObject.CompareTag("Enemy"))
        {
            var enemy = other.GetComponent<EnemyContoller>();
            enemy.health -= 10;
            if (enemy.health <= 0)
            {
                Destroy(other.gameObject);
            }

            PlayEffect();
        }
        else if (other.gameObject.CompareTag("Player"))
        {
            var player = other.GetComponent<SoliderController>();
            player.health -= 10;
            if (player.health <= 0)
            {
                Destroy(other.gameObject);
            }

            PlayEffect();
        }
    }
    private void PlayEffect()
    {
        // 播放粒子效果
        GameObject b = BulletHitPool.Instance.GetBulletHit();
        // 设置坐标和方向
        b.transform.position = transform.position;
        b.transform.LookAt(-transform.up);

        BulletPool.Instance.RecoverBullet(this.gameObject);
    }
}
